//
//  WBWelcomeView.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/7.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit
import SDWebImage

/// 欢迎视图
class WBWelcomeView: UIView {
    
    @IBOutlet weak var avatarImgView: UIImageView!
    @IBOutlet weak var tipLabel: UILabel!
    
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var widthConstraints: NSLayoutConstraint!
    class func welcomeView() -> WBWelcomeView {
        let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
        v.frame = UIScreen.main.bounds
        //从xib加载的视图大小默认是600x600
        return v
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //提示：initWithCoder只是刚从Xib二进制文件将视图加载完成，还没有和代码连线连接关系，所以开发时，千万不要在这里处理UI
    }
    override func awakeFromNib() {
        //1.url
        guard let urlString = WBNetworkManager.shared.userAccount.avatar_large, let imageUrl = URL(string: urlString) else {
            return
        }
        //2.FIXME:设置头像
        avatarImgView.sd_setImage(with: nil, placeholderImage: UIImage(named: "avatar_default_big"), options: .retryFailed, completed: nil)
        avatarImgView.layer.cornerRadius = widthConstraints.constant * 0.5
        avatarImgView.layer.masksToBounds = true
    }
    /// 视图被添加到window上，表示视图已经显示
    override func didMoveToWindow() {
        super.didMoveToWindow()
        //视图使用自动布局来设定的，只是设置了约束
        // - 当视图被添加到窗口上，根据父视图的大小，计算约束值，更新控件位置
        // - layoutIfNeeded会按照当前的约束直接更新控件的位置，执行之后，控件所在位置，就是xib布局制定的位置
        self.layoutIfNeeded()
        bottomConstraint.constant = bounds.height - 200
        //如果控件的frame还没有计算好，所有的约束会一起动画
        UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
            //更新约束
            self.layoutIfNeeded()
        }) { (_) in
            UIView.animate(withDuration: 1, animations: {
                self.tipLabel.alpha = 1
            }, completion:{ (_) in
               self.removeFromSuperview()
            })
        }
    }
}
